import time
import logging
import urllib.parse
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

logger = logging.getLogger(__name__)


class BilibiliPage:
    def __init__(self, driver):
        self.driver = driver
        self.home_url = "https://www.bilibili.com"
        self.home_window = None  # 首页窗口句柄

    def open_homepage(self):
        """打开首页并记录窗口句柄"""
        logger.info("打开B站首页")
        self.driver.get(self.home_url)
        self.driver.maximize_window()
        self.home_window = self.driver.current_window_handle  # 记录首页窗口
        time.sleep(3)
        self._close_popups()
        return self

    def _close_popups(self):
        """关闭首页弹窗"""
        try:
            # 关闭可能的登录弹窗或广告
            close_buttons = self.driver.find_elements(
                By.CSS_SELECTOR, ".bili-mini-close, .close, .banner-close"
            )
            for btn in close_buttons:
                if btn.is_displayed():
                    btn.click()
                    time.sleep(1)
        except Exception as e:
            logger.warning(f"关闭弹窗失败: {e}")

    def search_video(self, keyword):
        """在新窗口打开搜索结果，绝对不覆盖首页"""
        logger.info(f"搜索视频: {keyword}")

        # 确保在首页窗口操作
        self.driver.switch_to.window(self.home_window)

        # 编码关键词
        encoded_keyword = urllib.parse.quote(keyword)
        search_url = f"https://search.bilibili.com/all?keyword={encoded_keyword}"

        try:
            # 方法1: 通过搜索框在新窗口打开（推荐）
            search_input = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "input.nav-search-input"))
            )
            search_input.clear()
            search_input.send_keys(keyword)
            time.sleep(1)

            # 关键: 用JS强制在新窗口打开搜索结果，避免覆盖首页
            self.driver.execute_script(f'''
                window.open('{search_url}');
            ''')
            logger.info("在新窗口打开搜索结果")

        except Exception as e:
            logger.warning(f"搜索框操作失败，直接新窗口打开: {e}")
            # 方法2: 直接在新窗口打开搜索页
            self.driver.execute_script(f"window.open('{search_url}')")

        # 等待新窗口打开并切换
        WebDriverWait(self.driver, 10).until(
            lambda d: len(d.window_handles) > 1
        )
        # 切换到搜索结果页窗口（非首页的那个窗口）
        search_window = [h for h in self.driver.window_handles if h != self.home_window][0]
        self.driver.switch_to.window(search_window)

        # 验证搜索结果页加载完成
        WebDriverWait(self.driver, 15).until(
            EC.url_contains("search.bilibili.com")
        )
        logger.info(f"已切换到搜索结果页，URL: {self.driver.current_url}")
        return self.driver.current_url